﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Mysqlx;
using Newtonsoft.Json;
using ServiceStack;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Configuration;
using System.Linq;
using System.Linq.Expressions;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using ZH.Infrastructure.Attr;
using ZH.Infrastructure.Dto.Request.Login;
using ZH.Infrastructure.Dto.Request.Tech;
using ZH.Infrastructure.Dto.Request.Yuyue;
using ZH.Infrastructure.Dto.Response;
using ZH.Infrastructure.Dto.Response.admin;
using ZH.Infrastructure.Dto.Response.Article;
using ZH.Infrastructure.Dto.Response.Promotion;
using ZH.Infrastructure.Dto.Response.Tech;
using ZH.Infrastructure.Dto.Response.Yuyue;
using ZH.Infrastructure.EFCore.MySql;
using ZH.Infrastructure.IOC;
using ZH.Infrastructure.Redis;
using ZH.Infrastructure.Tools;
using ZH.Service.Interface;
using static Google.Protobuf.Reflection.FieldOptions.Types;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace ZH.Service.Instance
{
    [Inject_]
    public class Promotion_Service : Base_Service, I_Promotion_Service
    {
        private readonly Mobile_IOC _mobile_IOC;
        private readonly IConfiguration _configuration;
        public Promotion_Service(Mobile_IOC mobile_IOC, IConfiguration configuration)
        {
            _mobile_IOC = mobile_IOC;
            _configuration = configuration;
        }

        public async Task<Api_Response_Dto> Get_copywriting(int? page, int? limit, string? key)
        {
            var data = await _mobile_IOC._copywriting_EFCore
                .QueryAll(out int total,
                  Convert.ToInt32(page), Convert.ToInt32(limit),
                  true,
                  o => o.CId,
                    d => (string.IsNullOrEmpty(key) || d.Cbody.Contains(key))
                  ).ToListAsync();

            var type = _configuration["Dictionary_Type:Tech"];
            var dic = _mobile_IOC._dictionary_EFCore.QueryAll(d => d.DparentId == type).ToList();


            var query = from d in data
                        join c in dic on d.Ctype equals c.Did
                        select new Copywriting_Response_Dto
                        {
                            cId = d.CId,
                            ctype = d.Ctype,
                            tname = c.Dname,
                            cLength = d.CLength,
                            cbody = d.Cbody,
                            ctime = d.CTime.ToString(),
                        };



            return Result(1, "ok", new
            {
                total,
                query
            });
        }

        public async Task<Api_Response_Dto> Get_GL_record(int? page, int? limit, string? key)
        {
            var data = await _mobile_IOC._record_EFCore.QueryAll(out int total,
                  Convert.ToInt32(page), Convert.ToInt32(limit),
                  true,
                  o => o.RTime,
                    d => (string.IsNullOrEmpty(key) || d.RName.Contains(key))
                  ).ToListAsync();

            var pending = _mobile_IOC._record_EFCore.QueryAll(d => d.RState == 1).Count();
            var settled = _mobile_IOC._record_EFCore.QueryAll(d => d.RState == 0).Count();
            var totalCommission = _mobile_IOC._record_EFCore.QueryAll(d => d.RState == 0).Sum(d=>d.RCommission);
            return Result(1, "ok", new
            {
                total,
                data,
                pending,
                settled,
                totalCommission
            });

        }

        public async Task<Api_Response_Dto> Get_poster()
        {
            var data = await _mobile_IOC._poster_EFCore
                .QueryAll()
                .Select(d => new Poster_Response_Dto
                {
                    ptype = d.Ptype,
                    purl = d.Purl,
                    ptime = d.PTime
                }).ToArrayAsync();
            return Result(1, "ok", data);
        }

        public async Task<Api_Response_Dto> Get_record(User_Response_Dto? dto, string id)
        {

            var data = await _mobile_IOC._record_EFCore
                .QueryAll(d => d.RMid == id)
                .Select(d => new Record_Response_Dto
                {
                    name = d.RName,
                    time = d.RTime,
                    type = d.RType,
                    commission = d.RCommission,

                }).ToArrayAsync();
            return Result(1, "ok", data);
        }


        public async Task<Api_Response_Dto> Get_revenue(string user)
        {
            var now = DateTime.Now;
            int currentYear = now.Year;
            int currentMonth = now.Month;
            int currentDay = now.Day;

            // 一次查询获取所有需要的数据
            var records = await _mobile_IOC._record_EFCore
                // 只处理状态0和1的数据
                .QueryAll(d => d.RMid == user && (d.RState == 0 || d.RState == 1))
                .Select(d => new { d.RState, d.RCommission, d.RTime })
                .ToArrayAsync();

            // 计算三种情况的总和
            var result = new
            {
                //当天的收益
                ToDay =records
                .Where(r => r.RState == 0 && r.RTime.Year == currentYear && r.RTime.Month == currentMonth && r.RTime.Day == currentDay)
                .Sum(r => r.RCommission),

                // 状态0且当月的数据总和
                TotalState0CurrentMonth = records
                    .Where(r => r.RState == 0 && r.RTime.Year == currentYear && r.RTime.Month == currentMonth)
                    .Sum(r => r.RCommission),

                // 状态0且无月份限制的数据总和
                TotalState0AllTime = records
                    .Where(r => r.RState == 0)
                    .Sum(r => r.RCommission),

                // 状态1且无月份限制的数据总和
                TotalState1AllTime = records
                    .Where(r => r.RState == 1)
                    .Sum(r => r.RCommission)
            };

            return Result(1, "ok", result);
        }


        public async Task<Api_Response_Dto> Get_promotion_quantity(string user)
        {
            // 筛选当前用户的链接和二维码类型记录
            var records = await _mobile_IOC._record_EFCore
                .QueryAll(d => d.RMid == user && (d.RType == "链接" || d.RType == "二维码"))
                .Select(d => d.RType)
                .ToArrayAsync();

            // 分别统计两种类型的数量
            var linkCount = records.Count(r => r == "链接");
            var qrCodeCount = records.Count(r => r == "二维码");
            var totalCount = linkCount + qrCodeCount;

            // 封装结果
            var result = new
            {
                Total = totalCount,          // 总数量
                LinkCount = linkCount,       // 链接类型数量
                QrCodeCount = qrCodeCount    // 二维码类型数量
            };

            return Result(1, "获取成功", result);
        }


        public async Task<Api_Response_Dto> Sr_record(string id, string cz)
        {
            var data = await _mobile_IOC._record_EFCore.QueryAll(d => d.RId == id).FirstOrDefaultAsync();
            if (data == null)
            {
                return Result(0, "未找到");
            }
            if (cz == "结算")
            {
                data.RState = 0;
            }
            else
            {
                data.RState = 2;

            }
            _mobile_IOC._record_EFCore.Update(data);
            var reault = _mobile_IOC._record_EFCore.SaveChanges();

            return Result(reault, "操作成功");

        }
    }
}

